import re
from datetime import datetime, timedelta

from django.utils import timezone
from rest_framework import serializers

from MxShop.settings import REGEX_MOBILE
from rest_framework.validators import UniqueValidator

from users.models import UserProfile,VerifyCode


class SmsSerializer(serializers.Serializer):
    mobile = serializers.CharField(max_length=11)

    def validate_mobile(self, mobile):
        """
        校验手机号码
        :param mobile:
        :return:
        """
        # 手机号是否被注册
        if UserProfile.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError("手机号已经被注册")
        # 是否合法
        if not re.match(REGEX_MOBILE,mobile):
            raise serializers.ValidationError("手机号码非法")
        # 验证码发送频率，一分钟只能发送一次,根据数据库的add_time判断
        # 得到一分钟前的时间
        one_mintes_ago = datetime.now() - timedelta(hours=0,minutes=1,seconds=0)
        # 判断数据库验证码创建的时间是否小于一分钟前的时间
        if VerifyCode.objects.filter(add_time__gt=one_mintes_ago,mobile=mobile).count():
            raise serializers.ValidationError("60S内验证码只能发送一次")
        return mobile


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详情
    """
    class Meta:
        model = UserProfile
        fields = ("name", "gender", "birthday", "email","mobile")


class UserRegisterSerializer(serializers.ModelSerializer):
    """
    用户序列化器
    """

    code = serializers.CharField(required=True,max_length=4,min_length=4,help_text='验证码',label="验证码",
                                 write_only=True, # 序列化时不返回给前端
                                 error_messages={
                                     'required':"请输入验证码",
                                     'blank':"请输入验证码",
                                     'max_length':"验证码格式错误",
                                     'min_length':"验证码格式错误",
                                 })
    # 验证用户名是否存在
    username = serializers.CharField(required=True,allow_blank=False,label="用户名",
                                     validators=[UniqueValidator(queryset=UserProfile.objects.all(),message="用户已经存在")])
    password = serializers.CharField( style={'input_type': 'password'},help_text="密码", label="密码", write_only=True,)

    def validate_code(self, code):
        """
        验证码校验
        :param code:
        :return:
        """
        # 是否存在
        # 用户注册，以post方式提交注册信息，post的数据都保存在initial_data里面
        # username就是前端传递的用户注册的手机号，验证码按添加时间倒序排序，为了后面验证过期，错误等
        verify_recode = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by('-add_time')
        if verify_recode:
            last_recode = verify_recode[0]  # 最新发送的那条验证码
            # 得到五分钟之前的时间
            five_mintes_ago = datetime.now() - timedelta(hours=0, minutes=5, seconds=0)
            if five_mintes_ago > last_recode.add_time:
                raise serializers.ValidationError("验证码过期")

            if last_recode.code != code:
                raise serializers.ValidationError("验证码错误")
        else:
            raise serializers.ValidationError("验证码错误")


    def validate(self, attrs):
        """
        所有字段。attrs是字段验证合法之后返回的总的dict
        """
        # 前端没有传mobile值到后端username就是mobile，这里添加进来
        attrs['mobile'] = attrs['username']
        # code是自己添加得字段，数据库中并没有这个字段，验证完就删除掉
        del attrs['code']
        return attrs


    def create(self, validated_data):
        """
        密码加密
        :param validated_data:
        :return:
        """
        user = UserProfile.objects.create_user(**validated_data,)
        return user


    class Meta:
        model = UserProfile
        fields = ('username','code','mobile','password')









